package com.shuyuwl.utils;

import com.shuyuwl.configuration.FastDfsProperties;
import com.shuyuwl.core.enums.ResultEnum;
import com.shuyuwl.core.exception.SymServiceException;
import com.shuyuwl.core.utils.SpringContextUtil;
import com.shuyuwl.service.FileService;
import org.csource.common.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author: Tangnibal
 * @date: 2019年11月05日
 */
public class FastFileUploadUtil {

    /**
     * 文件上传
     * @param multipartFile  文件
     * @return 文件上传后的路径 example:http://192.168.77.186/group1/M00/00/00/wKhNul0Nk5mAZzFKAAEPcQxDQZY208.jpg;
     */
    public static String uploadFile(MultipartFile multipartFile){
        FastDfsProperties properties = SpringContextUtil.getBean(FastDfsProperties.class);
        String fastDfsLocation = properties.getFastDfsLocation();

        String uploadPath = "";
        String fileName = multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        try {
            FastDFSClientUtil dfsClientUtil = new FastDFSClientUtil();
            uploadPath = dfsClientUtil.uploadFile(multipartFile.getBytes(), ext);
        }catch (IOException e){
            throw new RuntimeException("上传的文件有误!");
        } catch (Exception e) {
            throw new RuntimeException("连接fastDfs服务失败，请检查fastDfs是否启动");
        }
        return fastDfsLocation+uploadPath;
    }

    /**
     * 保存文件到fastdfs并添加数据到数据库
     * @param multipartFile
     */
    public static com.shuyuwl.domain.File saveToFastDfsAndDatabase(MultipartFile multipartFile){
        FileService fileService = SpringContextUtil.getBean(FileService.class);
        com.shuyuwl.domain.File file = FileUpload.getFile(multipartFile);
        file.setFilename(multipartFile.getOriginalFilename());
        String fastDfsPath = uploadFile(multipartFile);
        file.setPath(fastDfsPath);
        fileService.save(file);
        return file;
    }


    /**
     * 从fastdfs文件服务器下载文件
     * @param inFile 文件在服务器上的地址 example:http://192.168.77.186/group1/M00/00/00/wKhNul0Nk5mAZzFKAAEPcQxDQZY208.jpg;
     * @return
     * @throws IOException
     */
    public static File fastDfsDownload(String inFile) throws IOException {
        FastDfsProperties properties = SpringContextUtil.getBean(FastDfsProperties.class);
        FileService fileService = SpringContextUtil.getBean(FileService.class);
        com.shuyuwl.domain.File sourceFile = fileService.getByPath(inFile);
        String fastDfsLocation = properties.getFastDfsLocation();
        //去掉服务器地址
        inFile = inFile.replace(fastDfsLocation,"");

        FastDFSClientUtil clientUtil = null;
        try {
            clientUtil = new FastDFSClientUtil();
        } catch (Exception e) {
            throw new RuntimeException("fastdfs连接失败!");
        }
        byte[] target = clientUtil.download_bytes(inFile);

        String fileName = sourceFile.getFilename();
        File inputFile = new File(fileName);
        if (inputFile.exists()){
            inputFile.delete();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(inputFile);
        fileOutputStream.write(target,0,target.length);
        fileOutputStream.flush();
        fileOutputStream.close();
        return inputFile;
    }

    /**
     * 根据文件id删除fasfdfs上的文件
     * @param fileId
     */
    public static void deleteByFileId(Long fileId){
        FileService fileService = SpringContextUtil.getBean(FileService.class);
        com.shuyuwl.domain.File file = fileService.get(fileId);
        //删除fastdfs文件
        deleteByPath(file.getPath());
        //删除数据库数据
        fileService.delete(fileId);
    }

    /**
     * 根据文件路径删除fasfdfs上的文件
     * @param path 文件路径 example:http://192.168.77.186/group1/M00/00/00/wKhNul0Nk5mAZzFKAAEPcQxDQZY208.jpg;
     */
    public static void deleteByPath(String path){
        FastDfsProperties properties = SpringContextUtil.getBean(FastDfsProperties.class);
        String fastDfsLocation = properties.getFastDfsLocation();
        FastDFSClientUtil clientUtil = null;
        try {
            clientUtil = new FastDFSClientUtil();
        } catch (Exception e) {
            throw new SymServiceException(ResultEnum.UNKOWN_ERROR);
        }
        clientUtil.delete_file(path.replace(fastDfsLocation,""));
    }
}
